<template>
  <div>
    <el-table :data="roleData" style="width: 100%">
      <el-table-column type="index" label="编号" width="60px" />
      <!-- <el-link type="primary" prop="roleName" label="角色名称" >primary</el-link> -->
      <el-table-column prop="roleName" label="角色名称">
        <template v-slot="scope">
          <el-link type="primary" @click="open(scope.row)">{{
            scope.row.roleName
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="creator" label="创建人" />
      <el-table-column prop="creationDate" label="创建日期">
        <template v-slot="scope">
          {{ scope.row.creationDate.substring(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateor" label="修改人" />
      <el-table-column prop="updatedate" label="修改日期">
        <template v-slot="scope">
          {{
            scope.row.updatedate ? scope.row.updatedate.substring(0, 10) : null
          }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300px">
        <template v-slot="scope">
          <el-button type="primary" size="small" @click="update(scope.row)"
            >修改</el-button
          >
          <el-button type="danger" size="small" @click="del(scope.row.roleId)"
            >删除</el-button
          >
          <el-button type="success" size="small" @click="pei(scope.row)"
            >分配员工</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 修改弹框 -->
    <el-dialog v-model="dialogVisible" title="更新角色" width="500">
      <template #footer>
        <div class="dialog-footer">
          <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="ruleForm.roleName" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                确定
              </el-button>
              <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </el-dialog>

    <!-- 分配人员弹框 -->
    <el-dialog v-model="updUser" :title="roleForm.name" width="500">
      <template #footer>
        <div class="dialog-footer">
          <el-container>
            <el-aside width="200px">
              <!-- 部门树 -->
              <el-tree
                ref="deptreeRef"
                style="max-width: 600px"
                :data="data"
                show-checkbox
                default-expand-all
                node-key="id"
                highlight-current
                :props="defaultProps"
                @change="getCheckedNodes()"
              />
            </el-aside>
            <el-container>
              <el-main>
                <!-- 员工树 -->
                <el-tree
                  ref="usertreeRef"
                  style="max-width: 600px"
                  :data="user"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  highlight-current
                  :props="defaultProps1"
                  @change="getCheckedNodes1()"
                />
              </el-main>
            </el-container>
          </el-container>

          <el-button type="primary" @click="save()">确定保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 点击角色名称弹框 -->
    <el-dialog v-model="clickRoleName" :title="roleForm.name1" width="600">
      <template #footer>
        <div class="dialog-footer">
          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="userName" label="姓名" />
            <el-table-column label="操作" v-slot="scope">
              <el-button type="primary" @click="pei(scope.row)">+</el-button>
              <el-button type="danger" @click="delUR(scope.row.userRoleId)"
                >X</el-button
              >
            </el-table-column>
          </el-table>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { el } from "element-plus/es/locales.mjs";
import { KongaUrl } from "@/axios/axiosHelp";
const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const router = useRouter();

//#region 角色信息显示+修改+删除

const roleData = ref([]);
//获取角色列表
const roleList = () => {
  KongaUrl.get("/user/api/Backed/GetRole").then((res) => {
    roleData.value = res.data.data;
  });
};

//修改角色弹框的显示/隐藏
const dialogVisible = ref(false);

//反填
const update = (role: any) => {
  dialogVisible.value = true;
  ruleForm.roleId = role.roleId;
  ruleForm.roleName = role.roleName;
  ruleForm.creationDate = role.creationDate;
  ruleForm.creator = role.creator;
};
//修改需要的参数
const ruleForm = reactive({
  roleId: 0,
  roleName: "",
  creator: "",
  creationDate: "",
  updateor: "",
});
//修改角色
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      KongaUrl
        .post("/userwriter/api/Addrole/updateRole", ruleForm)
        .then((res) => {
          if (res.data.code == 300) {
            ElMessage.success(res.data.message);
            dialogVisible.value = false;
            /* updateTime: new Date().toLocaleString(), */ // 更新修改时间
            roleList();
          } else {
            ElMessage.error(res.data.message);
          }
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//取消操作
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

//删除
const del = (id: any) => {
  ElMessageBox.confirm("确认删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    KongaUrl
      .post("/userwriter/api/Addrole/deleteRole", {
        roleId: id,
      })
      .then((res) => {
        if (res.data.code == 500) {
          ElMessage.success(res.data.message);
          roleList();
        } else {
          ElMessage.error(res.data.message);
        }
      });
  });
};

//#endregion

//#region 显示部门树+员工数+添加关系表

//分配员工弹框的显示/隐藏
const updUser = ref(false);

//角色信息相关参数
const roleForm = reactive({
  name: "",
  id: 0,
  userList: [],
  name1: "",
});
//分配员工
const pei = (row: any) => {
  roleForm.name = "请设置【" + row.roleName + "】角色的员工";
  roleForm.id = row.roleId;
  updUser.value = true;
};

//部门树
const deptreeRef: any = ref([]);

//部门树的数据
const data = [
  {
    label: "选择部门",
    children: [
      {
        id: 1,
        label: "IT信息部",
      },
      {
        id: 2,
        label: "人力资源部",
      },
      {
        id: 3,
        label: "财务部",
      },
      {
        id: 4,
        label: "销售部",
      },
      {
        id: 5,
        label: "行政部",
      },
    ],
  },
];

//部门树的配置
const defaultProps = {
  children: "children",
  label: "label",
};

//获取选中部门节点
const getCheckedNodes = () => {
  const checkdNodes = deptreeRef.value.getCheckedNodes();
  console.log(checkdNodes[0].id);

  KongaUrl
    .get("/user/api/DepUser/GetDepartmentUsers", {
      params: {
        DepartmentId: checkdNodes[0].id,
      },
    })
    .then((res) => {
      user.value[0].children = res.data.data;
    });
};

//员工树
const usertreeRef: any = ref([]);

//员工数据
const user = ref([
  {
    userId: 0,
    userName: "选择员工",
    children: [],
  },
]);

//员工树节点配置
const defaultProps1 = {
  children: "children",
  label: "userName",
  id: "userId",
};

//获取选中员工节点
const getCheckedNodes1 = () => {
  const checkdNodes1 = usertreeRef.value
    .getCheckedNodes()
    .map((node: any) => node.userId);
  roleForm.userList = checkdNodes1.filter((item: any) => item != 0);
};

//点击保存
const save = () => {
  KongaUrl
    .post("/userwriter/api/Addur/Adduserrole", {
      roleId: roleForm.id,
      userIds: roleForm.userList,
    })
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.message);
        updUser.value = false;
        tableDataList();
      } else {
        ElMessage.error("添加角色用户关系失败");
      }
    });
};

//#endregion

//点击角色名称弹框显示/隐藏
const clickRoleName = ref(false);

//获取当前行的角色id
const roleMsg = reactive({
  roleId: 0,
  roleName: "",
});
//点击蓝色角色名称
const open = (row: any) => {
  clickRoleName.value = true;
  roleForm.name1 = "属于角色【" + row.roleName + "】的员工如下";
  roleMsg.roleId = row.roleId;
  tableDataList();
};

const tableData = ref([]);

//显示角色对应的员工
const tableDataList = () => {
  KongaUrl
    .get("/user/api/Backed/GetRUDto", {
      params: {
        RoleId: roleMsg.roleId,
      },
    })
    .then((res) => {
      tableData.value = res.data.data;
    });
};

//点击X号
const delUR = (id: any) => {
  ElMessageBox.confirm("确定删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    KongaUrl
      .post("/userwriter/api/Addur/DelUserRole", {
        userRoleId: id,
      })
      .then((res) => {
        if (res.data.code == 500) {
          ElMessage.success(res.data.message);
          tableDataList();
        } else {
          ElMessage.error("删除失败");
        }
      });
  });
};
//验证
const rules = reactive<FormRules>({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});

//勾子函数
onMounted(() => {
  roleList();
});
</script>

<style scoped></style>